import numpy as np
import matplotlib.pyplot as plt
from PySide2.QtWidgets import QWidget, QVBoxLayout, QSizePolicy
from matplotlib.animation import FuncAnimation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas


class AnimatedTrigPlot(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout(self)
        self.canvas = FigureCanvas(plt.figure())
        self.layout.addWidget(self.canvas)
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.canvas.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.init_plot()

    def init_plot(self):
        self.ax = self.canvas.figure.add_subplot(111)  # 修正此行，避免解包错误
        self.ax.set_xlim(-1.5, 1.5)
        self.ax.set_ylim(-1.5, 1.5)
        self.ax.set_aspect('equal')
        self.ax.grid(True, linestyle='--', alpha=0.6)

        # Create a circle
        theta = np.linspace(0, 2 * np.pi, 300)
        self.circle_x = np.cos(theta)
        self.circle_y = np.sin(theta)
        self.ax.plot(self.circle_x, self.circle_y, 'gray', lw=1)

        # Create moving elements
        self.moving_dot, = self.ax.plot([], [], 'ro', markersize=8)
        self.line_x, = self.ax.plot([], [], 'b-', lw=1)
        self.line_y, = self.ax.plot([], [], 'g-', lw=1)
        self.angle_text = self.ax.text(-1.2, 1.2, '', fontsize=12, color='purple')

        # Animation
        self.anim = FuncAnimation(self.canvas.figure, self.update_plot, frames=np.linspace(0, 2 * np.pi, 180),
                                  interval=50, blit=True)

    def update_plot(self, frame):
        x, y = np.cos(frame), np.sin(frame)
        self.moving_dot.set_data([x], [y])
        self.line_x.set_data([x, x], [0, y])
        self.line_y.set_data([0, x], [y, y])
        self.angle_text.set_text(f'Angle: {np.degrees(frame):.1f}°')
        return self.moving_dot, self.line_x, self.line_y, self.angle_text


